package com.imagefinder;
	import java.io.BufferedReader;
	import java.io.ByteArrayInputStream;
	import java.io.IOException;
	import java.io.InputStreamReader;
	import java.io.StringReader;
import java.net.URLDecoder;
	import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

	import javax.swing.JOptionPane;
	import javax.xml.parsers.DocumentBuilder;
	import javax.xml.parsers.DocumentBuilderFactory;
	import javax.xml.parsers.ParserConfigurationException;

	import org.apache.commons.httpclient.*;
	import org.apache.commons.httpclient.methods.*;
	import org.apache.commons.httpclient.params.HttpMethodParams;
	import org.w3c.dom.Document;
	import org.w3c.dom.Element;
	import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.util.ServerConfigurationReader;


	public class GoogleImageFinder implements ImageFinder {
		 
	
		  public String getPageString(String sKey, int gCount) {
			  ArrayList picData=null;
			  String str=null;
		    // Create an instance of HttpClient.
		    HttpClient client = new HttpClient();
		    HostConfiguration Hconfig=client.getHostConfiguration();
		    try{
		    if(!ServerConfigurationReader.isDirect()){
		    	Map<String, String> proxyDetails=ServerConfigurationReader.getProxyDetails();
		    	Hconfig.setProxy((String)proxyDetails.get("proxyaddress"),Integer.parseInt(proxyDetails.get("proxyport")));
		    }
		    }catch(Exception e){
		    	System.out.println("Retrieveing proxy details failed....");
		    }

		    // Create a method instance.
		    GetMethod method = new GetMethod("http://images.google.com/images?q="+sKey.trim()+"&start="+(gCount*20+1)+"&filter=0");

		    // Provide custom retry handler is necessary
		    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
		    		new DefaultHttpMethodRetryHandler(3, false));

		    try {
		      // Execute the method.
		      int statusCode = client.executeMethod(method);

		      if (statusCode != HttpStatus.SC_OK) {
		        System.err.println("Method failed: " + method.getStatusLine());
		      }

		      // Read the response body.
		      byte[] responseBody = method.getResponseBody();
		      BufferedReader inputBuffer=new BufferedReader(new InputStreamReader( new ByteArrayInputStream(responseBody)));
		      str=inputBuffer.readLine();
				String tempStr=str;
				String ttempStr="";
				String tuStr="";
				while(tempStr!=null){
					tuStr=ttempStr;
					tempStr=inputBuffer.readLine();
					
					if(tempStr==null)
						break;
					ttempStr=tempStr;
					str+=tuStr;
				}
				
		    } catch (HttpException e) {
		      System.err.println("Fatal protocol violation: " + e.getMessage());
		      e.printStackTrace();
		    } catch (IOException e) {
		      System.err.println("Fatal transport error: " + e.getMessage());
		      e.printStackTrace();
		    } finally {
		      // Release the connection.
		      method.releaseConnection();
		    } 
		    		return str;      
		  }
		   
		public ArrayList handleStrresult(String googleString)
		{
			ArrayList<String> urls=new ArrayList<String>();
			int index=0;
			while(true){
			index=googleString.indexOf("imgurl=");
			if(index==-1)
				break;
			String temp=googleString.substring(index);
			index=temp.indexOf("&");
			String url=temp.substring(0+"imgurl=".length(),index);
			googleString=temp.substring(index);
			urls.add(url);
			//System.out.println(url);
			}
			return urls;
		}
		
		
		public ArrayList<String> getFulURLs(String googlePageString){
			ArrayList<String> urls=new ArrayList<String>();
			int index=0;
			while(true){
				index=googlePageString.indexOf("imgrefurl=");
				if(index==-1)
					break;
				String temp=googlePageString.substring(index);
				index=temp.indexOf("&");
				String url=temp.substring(0+"imgrefurl=".length(),index);
				googlePageString=temp.substring(index);
				urls.add(url);
			}
			return urls;
		}
	
		public LinkedHashMap<String, String> getResults(String SearchKey, int gCount) throws Exception{
			String pageString=getPageString(SearchKey, gCount);
			ArrayList<String> urls=handleStrresult(pageString);
			ArrayList<String> fUrls=getFulURLs(pageString);
			String[] temp=new String[urls.size()];
			/*for(int i=0;i<urls.size();i++){
				temp[i]=urls.get(i);
				temp[i]=temp[i].replaceAll("%2520", " ");
				temp[i]=temp[i].replaceAll("%20", " ");
			}*/
			LinkedHashMap<String, String> imageResults=new LinkedHashMap<String, String>();
			for(int i=0;i<urls.size();i++){
				String url= URLDecoder.decode(urls.get(i), "UTF-8");
				String sourceUrl= URLDecoder.decode(fUrls.get(i), "UTF-8");	
				imageResults.put(url,sourceUrl);
			}
			return imageResults;
		}
		
		
}
